package department.fc.common;

import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oracle.jrockit.jfr.RequestDelegate;

public class FrontController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// 1. 한글처리
		request.setCharacterEncoding("UTF-8");
		// client의 request를 처리하는 컨트롤러 로직
		String command = request.getParameter("command");
		Controller controller = HandlerMapping.getController(command);

		try {
			AttributeAndView av = controller.handleRequest(request, response);
			if (av.isRedirect()) {
				response.sendRedirect(av.getUrl());
			} else {
				Map attributes = av.getAttributes();
				if (attributes != null && attributes.size() != 0) {
					Set<Entry<String, Object>> entry = attributes.entrySet();
					for (Entry<String, Object> e : entry) {
						request.setAttribute(e.getKey(), e.getValue());

					}
				}

				RequestDispatcher rdp = request.getRequestDispatcher(av
						.getUrl());
				rdp.forward(request, response);

			}

		} catch (Exception e) {
			e.printStackTrace();
			throw new ServletException(e);
		}

	}
}
